//! Cluster模式Redis服务器实现

use crate::server::traits::ServerMode;
use crate::server::redis_service::{start_redis_service_with_mode, stop_redis_service, RedisService};
use crate::storage::RedisServerMode;
use crate::cluster::{ClusterConfig, ClusterNetworkManager};
use async_trait::async_trait;
use std::io;
use tokio::task::JoinHandle;
use tracing::{info, error};

/// Cluster模式Redis服务器
pub struct ClusterServer {
    config: ClusterConfig,
    cluster_handle: Option<JoinHandle<()>>,
    redis_service: Option<RedisService>,
    is_running: bool,
}

impl ClusterServer {
    /// 从配置文件创建新的Cluster服务器（自动检测格式）
    pub async fn new(config_path: &str) -> Result<Self, Box<dyn std::error::Error>> {
        use crate::config::load_config;
        
        let config = load_config(config_path)?;
        config.validate().map_err(|e| format!("配置验证失败: {e}"))?;
        
        Ok(Self {
            config,
            cluster_handle: None,
            redis_service: None,
            is_running: false,
        })
    }
    
    /// 从TOML配置文件创建新的Cluster服务器
    pub async fn from_toml(config_path: &str) -> Result<Self, Box<dyn std::error::Error>> {
        use crate::config::TomlConfigParser;
        use crate::config::ConfigLoader;
        
        let parser = TomlConfigParser;
        let config = parser.load_from_file(std::path::Path::new(config_path))?;
        config.validate().map_err(|e| format!("配置验证失败: {e}"))?;
        
        Ok(Self {
            config,
            cluster_handle: None,
            redis_service: None,
            is_running: false,
        })
    }
    
    /// 从配置创建新的Cluster服务器
    pub fn from_config(config: ClusterConfig) -> Self {
        Self {
            config,
            cluster_handle: None,
            redis_service: None,
            is_running: false,
        }
    }
}

#[async_trait]
impl ServerMode for ClusterServer {
    async fn start(&mut self) -> io::Result<()> {
        if self.is_running {
            return Ok(());
        }

        info!("🚀 启动Redis-rs2 Cluster模式服务器");
        info!("🎯 节点ID: {}", self.config.node_id);
        info!("📍 Redis端口: {}", self.config.redis_port);
        info!("📍 集群端口: {}", self.config.cluster_port);
        
        // 按照Redis官方实现：集群功能先启动，成功后才启动Redis功能
        
        // 1. 先启动集群通信功能
        info!("🔗 步骤 1/2: 启动集群通信服务...");
        let _cluster_addr = self.config.cluster_addr();
        let cluster_config = self.config.clone();
        
        let cluster_handle = tokio::spawn(async move {
            match ClusterNetworkManager::new(cluster_config).await {
                Ok(mut network_manager) => {
                    if let Err(e) = network_manager.bind().await {
                        error!("⚠️ 集群网络管理器绑定失败: {}", e);
                        return;
                    }
                    if let Err(e) = network_manager.start().await {
                        error!("⚠️ 集群网络管理器启动失败: {}", e);
                    }
                }
                Err(e) => {
                    error!("⚠️ 创建集群网络管理器失败: {}", e);
                }
            }
        });
        
        self.cluster_handle = Some(cluster_handle);
        
        // 给集群服务一点时间初始化
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        info!("✅ 集群通信服务启动成功");
        
        // 2. 再启动Redis服务功能（集群模式）
        info!("🔗 步骤 2/2: 启动Redis服务功能（集群模式）...");
        let redis_addr = self.config.redis_addr();
        let redis_service = start_redis_service_with_mode(&redis_addr, RedisServerMode::Cluster).await?;
        self.redis_service = Some(redis_service);
        
        self.is_running = true;
        
        info!("✅ Cluster模式服务器启动成功");
        info!("💡 Redis客户端连接: redis://127.0.0.1:{}", self.config.redis_port);
        info!("💡 集群通信端口: {}", self.config.cluster_port);
        
        Ok(())
    }

    async fn stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }

        info!("🛑 停止Cluster模式服务器");
        
        // 先停止Redis服务
        if let Some(redis_service) = self.redis_service.take() {
            stop_redis_service(redis_service).await?;
        }
        
        // 再停止集群服务
        if let Some(handle) = self.cluster_handle.take() {
            handle.abort();
        }
        
        self.is_running = false;
        info!("✅ Cluster模式服务器已停止");
        Ok(())
    }

    fn is_running(&self) -> bool {
        self.is_running
    }
    
    fn get_mode(&self) -> RedisServerMode {
        RedisServerMode::Cluster
    }
}